import React from 'react';
import { connect } from 'dva';
import { Form, Input, Divider, Modal,Checkbox, Select, DatePicker } from 'antd';
import moment from 'moment';
const CheckboxGroup = Checkbox.Group;
const Option = Select.Option;
const { TextArea } = Input;
const dateFormat = 'YYYY-MM-DD';
const formItemLayout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 19,
  },
};

const options2 = [
  { label: 'wifi', value: 'wifi' },
  { label: '4G', value: '4G' },
  { label: '3G', value: '3G' },
  { label: '蓝牙', value: '蓝牙'},
  { label: '2.4G', value: '2.4G'},
  { label:'有线',value:'有线'}
];

const options1 = [
  { label: '功能测试', value: '功能测试' },
  { label: '兼容性测试', value: '兼容性测试' },
  { label: '多语言测试', value: '多语言测试' },
  { label: '正确性测试', value: '正确性测试' },
  { label: '用户界面测试', value: '用户界面测试'},
  { label: '易用性测试', value: '易用性测试'},
  { label: '本地化测试', value: '本地化测试' },
  { label: '安装升级测试', value: '安装升级测试'},
  { label: '机型适配测试', value: '机型适配测试'},
  { label: '网络覆盖测试', value: '网络覆盖测试'},
  { label: '稳定性测试', value: '稳定性测试' },
  { label: '安全性测试', value: '安全性测试' },
];

const platform = [{key:'pc',value:'pc'}, {key:'web',value:'web'}, {key:'移动端',value:'移动端'}]

// const equipment ={
//   pc: ['win7', 'win8', 'mac'],
//   web: ['chrome', 'firefox', 'QQ浏览器'],
//   移动端:['小米(android5.0)','三星(android6.0)','ipad(ios11)','iphone6(ios9)']
// };
@connect(({testreport,userSelect, loading }) => ({
  testreport,
  searchUsers: userSelect.searchUsers,
  bVisible: testreport.basicvisible,
  loading: loading.models.testreport
}))
export default Form.create()(
    class extends React.PureComponent {
      state = {
        eqp: [],
        secondEqm: [],
      }

      componentDidMount() {
        this.props.dispatch({
          type: 'userSelect/search',
          payload: { roleId: 3 }
        })

        this.props.dispatch({
          type:'testreport/getDataArray'
        })
        this.initializeBasicData();
      }

      configOption = (users) => {
        let options = _.isEmpty(users) ? null :
          this.props.searchUsers.map(user => <Option key={user.realName} >{`${user.realName}`}</Option>) 
        return options;
      }

      initializeBasicData = () =>{
        let equipment =this.props.equipment
        if(equipment){
          this.setState({
            eqp: equipment[platform[0].value],
          })
        }
      }

      handlePlatformChange = (value) => {
        let equipment =this.props.equipment
        this.props.form.setFieldsValue({
          equipment:equipment[value]?equipment[value][0]:[]
        })
        this.setState({
          eqp: equipment[value],
        });
      }
    
      onSecondEquipmentChange = (value) => {
        this.setState({
          secondEqm: value,
        });
      }
      handleCancel = () => {
        this.props.dispatch({
          type: 'testreport/setFormModalVisible',
          payload: false
        })
        this.props.form.resetFields();
      };

      handleOK = (e) => {
        const form = this.props.form;
        form.validateFields((err, values) => {
          let arr = this.props.equipment[values.type]?this.props.equipment[values.type]:[]
          let equipment = values.equipment
          let newequipment = []
          equipment.map((r)=>{
            if(arr.indexOf(r)==-1){
              newequipment.push({type:values.type?values.type:this.props.data.type,name:r})
            }
          })
          if(newequipment.length>0){
            this.props.dispatch({
              type:'testreport/addNewBasicData',
              payload:newequipment
            })
          }
          if (err) {
            return;
          }
          if (!err) {
            let data = {
              status: values.testConclusion === 'pass'? 1:(values.testConclusion ==='fail'?0:this.props.data.status),
              startTime:values.testStartTime? values.testStartTime.format('YYYY-MM-DD'):null,
              endTime :values.testEndTime? values.testEndTime.format('YYYY-MM-DD'):null,
              workload:values.testTime? values.testTime:null,
              tester:values.testers.join('--'),
              type: values.ptf? values.ptf:null,
              equipment:values.equipment? values.equipment.join('--'):null,
              network: values.network? values.network.join('--'):null,
              testRange:values.testRange? values.testRange.join('--'):null,
              id:this.props.data.key
            }
            this.props.dispatch({
              type:'testreport/editBasicReport',
              payload: data
            })

            this.props.dispatch({
              type: 'testreport/setFormModalVisible',
              payload: false
            })
          }
          this.props.form.resetFields();
        });
      };

      defaultTime =(date)=>{
        if(date!=='--'){
          return moment(date, dateFormat)
        }else{
          return null
        }
      }

      render() {
        const { getFieldDecorator } = this.props.form;
        const {eqp} = this.state;
        const reportData =this.props.data
        let searchOutUsers = this.props.searchUsers;        
        const options = this.configOption(searchOutUsers);
        return (
          <Modal
            visible={this.props.visible}
            title="基本信息编辑"
            okText="确定"
            cancelText="取消"
            destroyOnClose={this.props.visible}
            onCancel={this.handleCancel}
            onOk={this.handleOK}
            width={595}
          >
            <p>项目：</p>
            
            <Form layout="horizontal" >
              {/* <Form.Item {...formItemLayout}>
                {
                  getFieldDecorator('id', {
                    rules: [{ required: true }],
                    initialValue: data.id
                  })
                    (<Input type="hidden" />)
                }
              </Form.Item> */}
              
              <Form.Item {...formItemLayout} label="测试任务名称">
                {getFieldDecorator('testTask', {
                  initialValue: `${reportData.name} ${reportData.version}`,
                  rules: [
                    { required: true },
                  ],
                })(<Input  disabled = {true} />)}
              </Form.Item>

              <Form.Item {...formItemLayout} label="测试结论">
                {getFieldDecorator('testConclusion', {
                  initialValue: reportData.testResult,
                  rules: [{ required: false, message: '请选择测试结论' }],
                })(
                  <Select >
                    <Option value="pass">通过</Option>
                    <Option value="fail">不通过</Option>
                  </Select>
                )}
              </Form.Item>
              
              <Form.Item {...formItemLayout} label="测试开始时间">
                {getFieldDecorator('testStartTime', {
                  initialValue: this.defaultTime(reportData.startTime),
                  rules: [
                    { required: false, message: '请选择测试开始时间' },
                  ],
                })(
                    <DatePicker
                    placeholder="Start"
                    />
                )}
              </Form.Item>

              <Form.Item {...formItemLayout} label="测试结束时间">
                {getFieldDecorator('testEndTime', {
                   initialValue: this.defaultTime(reportData.endTime),
                  rules: [
                    { required: false, message: '请选择测试完成时间' },
                  ],
                })(
                    <DatePicker
                      placeholder="End"
                    />
                )}
              </Form.Item>
              
              <Form.Item {...formItemLayout} label="执行工作量">
                {getFieldDecorator('testTime', {
                  initialValue: reportData.workload,
                  rules: [
                    { required: false, message: '请输入测试执行工作量' },
                  ],
                })(<Input placeholder="天/人" />)}
              </Form.Item>

              <Form.Item {...formItemLayout} label="执行人员">
                {getFieldDecorator('testers', {
                  initialValue:reportData.tester,
                  rules: [
                    { required: true, message: '请选择测试人员' },
                  ],
                })(
                  <Select
                    mode="multiple"
                    placeholder="Please select"
                  >
                    {options}
                    
                  </Select>  
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="测试版本">
                {getFieldDecorator('testVersion', {
                  initialValue: reportData.version,
                  rules: [
                    { required: true},
                  ],
                })(<Input  disabled = {true} />)}
              </Form.Item>

              <Form.Item {...formItemLayout} label="网络">
                {getFieldDecorator('network', {
                  initialValue: reportData.network,
                  rules: [
                    { required: false},
                  ],
                })(
                  <CheckboxGroup options={options2} />
                )}
              </Form.Item>  

              <Form.Item {...formItemLayout} label="平台">
                {getFieldDecorator('ptf', {
                  initialValue: reportData.type,
                  rules: [
                    { required: false},
                  ],
                })(
                    <Select
                      style={{ width: 120 }}
                      onChange={this.handlePlatformChange}
                    >
                      {platform.map(platform => <Option key={platform.value}>{platform.key}</Option>)}
                    </Select>
                 
                )}
              </Form.Item>  
             
              <Form.Item {...formItemLayout} label='设备'>
              {getFieldDecorator('equipment', {
                  initialValue: reportData.equipment,
                  rules: [
                    { required: false},
                  ],
                })(
                  
                    <Select
                      mode="tags"
                      style={{ width: '100%' }}
                      onChange= {this.onSecondEquipmentChange}
                    >
                      {eqp.map(equipment => <Option key={equipment}>{equipment}</Option>)}
                    </Select>
                )}
              </Form.Item> 

              <Form.Item {...formItemLayout} label="测试范围">
                {getFieldDecorator('testRange', {
                  initialValue:reportData.testRange,
                  rules: [
                    { required: false},
                  ],
                })(
                  <CheckboxGroup options={options1}  />
                )}
              </Form.Item>  

            </Form>
          </Modal>
        );
      }
    }
  );
